﻿using System;
using System.Drawing;
using RibbonLib.Interop;
using pub.CmdUI.Cmd;
using pub.CmdUI.UI.Control;
using pub.NET20Fix;

namespace todo.Ribbon.CmdUI
{
    public class RibbonColorPickerUI : IItemsControlUI
    {
        private RibbonColorPicker _colorPicker;
        private Action _triggerCallback;

        public bool ReflectActiveColor { get; set; }

        public RibbonColorPickerUI(RibbonColorPicker colorPicker)
        {
            _colorPicker = colorPicker;

            colorPicker.OnSelect += colorPicker_OnSelect;
        }

        private void colorPicker_OnSelect()
        {
            if (_triggerCallback != null)
            {
                _triggerCallback();
            }
        }

        public Action TriggerCallback
        {
            set { _triggerCallback = value; }
        }

        public Bitmap Icon
        {
            set { throw new NotImplementedException(); }
        }

        public string Label
        {
            set { throw new NotImplementedException(); }
        }

        public string Tooltip
        {
            set { throw new NotImplementedException(); }
        }

        public void Update(ICmd cmd)
        {
            _colorPicker.Enabled = cmd.State.Enabled;

            if (!ReflectActiveColor)
            {
                return;
            }
            var itemsCmdState = cmd as IItemsCmdState;
            var color = itemsCmdState.SelectedIndex;
            if (color.HasValue)
            {
                _colorPicker.ColorType = SwatchColorType.RGB;
                _colorPicker.Color = Color.FromArgb(color.Value);
            }
            else
            {
                _colorPicker.ColorType = SwatchColorType.NoColor;
            }
        }

        public int? SelectedItemIndex
        {
            get
            {
                if (_colorPicker.ColorType == SwatchColorType.NoColor)
                {
                    return null;
                }
                else
                {
                    return _colorPicker.Color.ToArgb();
                }
            }
        }
    }
}